﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using CrystalFontzLCD;
using System.Configuration;

namespace SecondaryLCDControl
{
    //[StructLayout(LayoutKind.Sequential)]
    //private struct RECT
    //{
    //    public int left;
    //    public int top;
    //    public int right;
    //    public int bottom;
    //}
    
    public partial class Form1 : Form
    {
        bool KeepChecking = false;

        bool KeepUpdatingScn = false;

        bool ScreenRestartNeeded = false;

        Thread worker;
        Thread runScreen;

        LCDPanel lcdscreen; /*= new LCDPanel(LCDType.CrystalFontz632, "COM2", 19200);*/
        

        #region Screen Monitoring Code
        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }

        [DllImport("user32.dll")]
        private static extern bool GetWindowRect(HandleRef hWnd, [In, Out] ref RECT rect);

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        public static bool IsForegroundFullScreen()
        {
            return IsForegroundFullScreen(null);
        }

        public static bool IsForegroundFullScreen(Screen screen)
        {
            if (screen == null)
            {
                screen = Screen.PrimaryScreen;
            }
            RECT rect = new RECT();
            GetWindowRect(new HandleRef(null, GetForegroundWindow()), ref rect);
            return new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top).Contains(screen.Bounds);
        }
        #endregion
        public Form1()
        {
            InitializeComponent();
            LoadLCDSettings();
            worker = new Thread(CheckIfFullScreen);
            
            //lc1.Write(Command.HideCursor);

            runScreen = new Thread(RunScreen);
            //runScreen.Start();
            

        }
        private void LoadAppSettings()
        {
        }

        private void LoadLCDSettings()
        {
            LCDType lcdscr;
            string COM = "";
            int baud = 0;

            //improvement planned for next version on loading LCDType....
            string tLCDType = ConfigurationManager.AppSettings["LCDType"].ToString();
            if (tLCDType == "CrystalFontz632")
                lcdscr = LCDType.CrystalFontz632;
            else
                lcdscr = LCDType.CrystalFontz634;

            COM = ConfigurationManager.AppSettings["LCDCOMPRT"].ToString();

            baud = Int32.Parse(ConfigurationManager.AppSettings["COMBAUD"].ToString());
            try
            {
                lcdscreen = new LCDPanel(lcdscr, COM, baud); // move init code into own method that accepts each one as parameter
            }
            catch (Exception ex)
            {
                //lcdscreen.Dispose();
            }

            txtLCDComprt.Text = COM;
            txtBaud.Text = baud.ToString();
            cmbLCDTypes.SelectedIndex = cmbLCDTypes.FindStringExact(tLCDType);

        }

        private void SaveAppSettings()
        {
            Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            conf.AppSettings.Settings.Remove("LCDCOMPRT");
            conf.AppSettings.Settings.Add("LCDCOMPRT", txtLCDComprt.Text);
            conf.AppSettings.Settings.Remove("COMBAUD");
            conf.AppSettings.Settings.Add("COMBAUD", txtBaud.Text);
            conf.AppSettings.Settings.Remove("LCDType");
            conf.AppSettings.Settings.Add("LCDType", cmbLCDTypes.SelectedItem.ToString());
            conf.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        private void RunScreen()
        {
            while (KeepUpdatingScn)
            {
                lcdscreen.SetContrast(45);
                lcdscreen.Write(Command.HideCursor);
                Thread.Sleep(1000);
                lcdscreen.WriteToRow(MessageClass.time, 0);
                lcdscreen.WriteToRow(MessageClass.date, 1);
            }
        }
        private void CheckIfFullScreen()
        {
            while (KeepChecking)
            {
                MessageClass.time += IsForegroundFullScreen().ToString();
                if (IsForegroundFullScreen())
                {
                    string t = DateTime.Now.ToLocalTime().ToLongTimeString();
                    MessageClass.time = t;
                    string d = DateTime.Now.ToShortDateString();
                    MessageClass.date = d;
                }
                else
                {
                    MessageClass.time = "";
                    MessageClass.date = "";
                    lcdscreen.Clear();
                }
                Application.DoEvents();
                MessageClass.allowupdate = true;
                Thread.Sleep(1000);
                MessageClass.allowupdate = false;
                
            }
        }

        private void Form1_Click(object sender, EventArgs e)
        {

        }

        private void richTextBox1_Click(object sender, EventArgs e)
        {   
        }

        private void sTARTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            KeepChecking = true;
            KeepUpdatingScn = true;
            if (worker.ThreadState == ThreadState.Suspended)
            {
                worker.Resume();
            }
            else
            {
                worker.Start();
                runScreen.Start();

            }
        }

        private void sTOPToolStripMenuItem_Click(object sender, EventArgs e)
        {
            KeepChecking = false;
            KeepUpdatingScn = false;
            if (worker.ThreadState == ThreadState.Running)
            {
                worker.Suspend();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            KeepChecking = false;
            KeepUpdatingScn = false;
            if (worker.ThreadState == ThreadState.Suspended)
            {
                worker.Resume();
                worker.Abort();
            }
            
            Application.Exit();
        }

        private void editSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Opacity = 100.00;
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutLCDControl about = new AboutLCDControl();
            about.ShowDialog();
            about.Dispose();
        }

        private void btnsSave_Click(object sender, EventArgs e)
        {
            SaveAppSettings();
            LoadLCDSettings();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.00;
        }
    }
}
